//
//  LoginViewController.m
//  1243
//
//  Created by 我的 on 16/3/25.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "LoginViewController.h"
#import "CaptchaView.h"
#import "RegisterFirstViewController.h"
#import "BaseNavController.h"
#import "NetWorkTools.h"
#import "MerchantsApplyForVC.h"
#import "MeViewController.h"

@interface LoginViewController ()
<UITextFieldDelegate, UIAlertViewDelegate>
{
    CaptchaView *authCodeView;
    UITextField *_input;
}
@property (weak, nonatomic) IBOutlet UITextField *authTextField;
@property (weak, nonatomic) IBOutlet UIView *authView;
@property (weak, nonatomic) IBOutlet UITextField *PhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *PassWordNum;
@property (weak, nonatomic) IBOutlet UIImageView *BgImageVIew;

@property (nonatomic,strong) NSDictionary *logInDict;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.BgImageVIew.image = [UIImage imageNamed:@"huanya"];
//    self.BgImageVIew.contentMode = UIViewContentModeScaleToFill;

    //显示验证码界面
    authCodeView = [[CaptchaView alloc] initWithFrame:CGRectMake(0, 0, self.authView.bounds.size.width, self.authView.bounds.size.height)];
    [self.authView addSubview:authCodeView];
    
    self.authTextField.delegate = self;
    self.PassWordNum.delegate = self;
    self.PassWordNum.tag = 100;
    
    //添加输入框
    self.authTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.authTextField.backgroundColor = [UIColor clearColor];
    self.authTextField.returnKeyType = UIReturnKeyDone;
    self.authTextField.delegate = self;
    self.authTextField.tag = 100;
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem backBarButtonItemWithImage:[UIImage imageNamed:@"jiantou"] highImage:[UIImage imageNamed:@"jiantou"] target:self action:@selector(backToPre) forControlEvents:UIControlEventTouchUpInside title:@"返回"];
}

- (void)backToPre {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 输入框代理，点击return 按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //判断输入的是否为验证图片中显示的验证码
    if ([self.authTextField.text isEqualToString:authCodeView.authCodeStr])
    {
        //正确弹出警告款提示正确
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您" message:@"验证成功" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alview show];
    }
    else
    {
        //验证不匹配，验证码和输入框抖动
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-20,@20,@-20];
        //        [authCodeView.layer addAnimation:anim forKey:nil];
        [self.authTextField.layer addAnimation:anim forKey:nil];
    }
    
    return YES;
}

#pragma mark 警告框中方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (self.logInDict.count != 0) {
        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
    }
    
    //清空输入框内容，收回键盘
    if (buttonIndex==0)
    {
        self.authTextField.text = @"";
        [self.authTextField resignFirstResponder];
    }
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag == 101|| textField.tag == 100) {
        CGRect frame = textField.frame;
        int offset = frame.origin.y + 80 - (self.view.frame.size.height - 216.0);//键盘高度216
        
        //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
        if(offset > 0)
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        
        [UIView commitAnimations];
        
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //    NSLog(@"%@", textField.text);
}


#pragma mark - 点击返回
- (IBAction)clickBackBtn:(UIButton *)sender {
    NSDictionary *dict  = [ReadLoginData readLoginData];
    
    if (dict.count) {
        // 已登录
        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        
        
    }
}

- (IBAction)clickLoginBtn:(UIButton *)sender {
    //判断输入的是否为验证图片中显示的验证码
    if ([self.authTextField.text isEqualToString:authCodeView.authCodeStr])
    {
        [self registerLogInTextField];
        
        if ([self isMobileNumber:self.PhoneNum.text]) {
            NSDictionary *dict = @{
                                   @"PhoneNum":self.PhoneNum.text,
                                   @"Password":self.PassWordNum.text
                                   };
            
            [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"USERLOGIN" completeBlock:^(id object) {
                NSString *string = [object objectForKey:@"Message"];
                
                string = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                //            NSLog(@"%@",string);
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 1111;
                [alert show];
                
                
                self.logInDict = [NetWorkTools dictionaryWithJsonString:[object objectForKey:@"BackData"]];
                
                [ReadLoginData savelogindataToLocal:self.logInDict];
                
                //            NSLog(@"%@",object);
                
            }];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确格式的手机号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
            
            
        }
        

        
        
    }
    else
    {
        //验证不匹配，验证码和输入框抖动
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
        anim.repeatCount = 1;
        anim.values = @[@-20,@20,@-20];
        //        [authCodeView.layer addAnimation:anim forKey:nil];
        [self.authTextField.layer addAnimation:anim forKey:nil];
    }
}

- (IBAction)back:(id)sender {
    
//    [self dismissViewControllerAnimated:YES completion:^{
//        
//    }];
     [self.navigationController popViewControllerAnimated:YES];

}
//商户注册
- (IBAction)commercialRegister:(id)sender {
    

    
      [self presentViewController:[[BaseNavController alloc] initWithRootViewController:[[MerchantsApplyForVC alloc] init]] animated:YES completion:nil];
}

- (void)registerLogInTextField {
    [self.authTextField resignFirstResponder];
    [self.PhoneNum resignFirstResponder];
    [self.PassWordNum resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self registerLogInTextField];
}

- (IBAction)clickGotoRegisterVC:(UIButton *)sender {
    
    [self presentViewController:[[BaseNavController alloc] initWithRootViewController:[[RegisterFirstViewController alloc] init]] animated:YES completion:nil];
}
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188, 183
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186 145
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189  181
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end
